package com.exam.serviceimpl;
import com.exam.entity.JudgeQuestion;
import com.exam.mapper.JudgeQuestionRepository;
import com.exam.mapper.JudgeQuestionRepository;
import com.exam.service.JudgeQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class JudgeQuestionServiceImpl implements JudgeQuestionService {

    @Autowired
    private JudgeQuestionRepository judgeQuestionRepository;

    @Override
    public JudgeQuestion addJudgeQuestion(JudgeQuestion judgeQuestion) {
        if (checkDuplicate(judgeQuestion)) {
            throw new IllegalArgumentException("Duplicate judge question exists!");
        }
        return judgeQuestionRepository.save(judgeQuestion);
    }

    @Override
    public JudgeQuestion updateJudgeQuestion(Long id, JudgeQuestion judgeQuestion) {
        JudgeQuestion existing = judgeQuestionRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Judge question not found!"));
        existing.setSubject(judgeQuestion.getSubject());
        existing.setQuestion(judgeQuestion.getQuestion());
        existing.setAnswer(judgeQuestion.getAnswer());
        return judgeQuestionRepository.save(existing);
    }

    @Override
    public void deleteJudgeQuestion(Long id) {
        if (!judgeQuestionRepository.existsById(id)) {
            throw new IllegalArgumentException("Judge question not found!");
        }
        judgeQuestionRepository.deleteById(id);
    }

    @Override
    public JudgeQuestion getJudgeQuestionById(Long id) {
        return judgeQuestionRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Judge question not found!"));
    }

    @Override
    public List<JudgeQuestion> getAllJudgeQuestions() {
        return judgeQuestionRepository.findAll();
    }

    @Override
    public boolean checkDuplicate(JudgeQuestion judgeQuestion) {
        return judgeQuestionRepository
                .findBySubjectAndQuestionAndAnswer(judgeQuestion.getSubject(), judgeQuestion.getQuestion(), Boolean.valueOf(judgeQuestion.getAnswer()))
                .isPresent();
    }

    @Override
    public void importJudgeQuestions(List<JudgeQuestion> judgeQuestions) {
        for (JudgeQuestion judgeQuestion : judgeQuestions) {
            if (!checkDuplicate(judgeQuestion)) {
                judgeQuestionRepository.save(judgeQuestion);
            }
        }
    }
    @Override
    public Page<JudgeQuestion> getAllJudgeQuestions(Pageable pageable) {
        return judgeQuestionRepository.findAll(pageable);
    }
}